package com.administrator.cloudapplication.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.administrator.cloudapplication.R;
import com.administrator.cloudapplication.activitys.NewsDetailActivity;
import com.administrator.cloudapplication.adapter.NewsListItemAdapter;
import com.administrator.cloudapplication.base.BaseFragment;
import com.administrator.cloudapplication.callback.ReqCallBack;
import com.administrator.cloudapplication.constant.Urls;
import com.administrator.cloudapplication.models.BannerModel;
import com.administrator.cloudapplication.models.NewsListModel;
import com.administrator.cloudapplication.tools.BannerUtils;
import com.administrator.cloudapplication.tools.GsonUtils;
import com.administrator.cloudapplication.tools.HttpUtils;
import com.administrator.cloudapplication.tools.UrlUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 本页面是第一个页面的组成页面，主要做两种网络请求：轮播图的获取和新闻列表的获取。
 */

public class NewsFragment extends BaseFragment implements ReqCallBack, BannerUtils.OnPageSelected, PullToRefreshBase.OnRefreshListener2 {
    View mView;
    PullToRefreshListView refreshListView;//获取可以下拉刷新，上拉加载的ListView控件
    ViewPager vp_carousel;
    NewsListItemAdapter mNewsListItemAdapter;
    ArrayList<NewsListModel.DataBean.NewsListBean> mNewsListBean = new ArrayList<>();
    private static final String ARG_PARAM = "param";//定义静态变量，可以用来在页面之间传递
    TextView carousel_title, carousel_page;
    String params;
    List<String> mImages = new ArrayList<>();
    List<String> mTitles = new ArrayList<>();
    int page = 2;
    private List<BannerModel.DataBean.ImglistBean> mBannerList = new ArrayList<>();

    @Override
    protected void initPrepare() {

    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        requestWeb();
    }


    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_news, container, false);
        initQView();
        return mView;
    }


    private void initQView() {
        refreshListView = (PullToRefreshListView) mView.findViewById(R.id.pull_refresh_list);
        refreshListView.setOnRefreshListener(this);//为ListView添加上拉下拉的监听事件
        //为新闻列表的适配器添加数据
        mNewsListItemAdapter = new NewsListItemAdapter(getActivity(), mNewsListBean);
        //将适配器里的值赋给ListView列表
        refreshListView.setAdapter(mNewsListItemAdapter);
        //为ListView用代码动态的写一个headerView来放轮播图
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        //获取到headerView轮播图的布局文件
        View headerView = getActivity().getLayoutInflater().inflate(R.layout.header_view, refreshListView, false);
        headerView.setLayoutParams(layoutParams);
        //实例化获取到轮播图的所有控件
        vp_carousel = (ViewPager) headerView.findViewById(R.id.carousel_vp);
        carousel_title = (TextView) headerView.findViewById(R.id.carousel_title);
        carousel_page = (TextView) headerView.findViewById(R.id.carousel_page);
        //将写好的headerView添加到ListView里
        ListView lv = refreshListView.getRefreshableView();
        lv.addHeaderView(headerView);
        //新闻列表的点击事件，需要将列表里新闻的id和title传递给跳转的下一个页面
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                String nid = mNewsListBean.get(i - 2).getId();
                String title = mNewsListBean.get(i - 2).getTitle();
                Intent intent = new Intent();
                intent.setClass(getActivity(), NewsDetailActivity.class);
                intent.putExtra("nid", nid);
                intent.putExtra("title", title);
                startActivity(intent);
            }
        });
    }

    //系统的一个传参方法，也可以自己写，但没有系统的方便
    public static NewsFragment newInstance(String param) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    private void requestWeb() {
        requestWebData(1);
    }

    private void requestWebData(int page) {
        //轮播图的网络请求
        requestBanner();
        //新闻列表的网络请求
        requesList(page);
    }

    private void requestBanner() {
        params = this.getArguments().getString(ARG_PARAM);
        String[] param = {params};
        String url = UrlUtils.convertUrl(param, Urls.BANNER_URL);
        HttpUtils.getInstance(getActivity()).requestAsyn(url, HttpUtils.TYPE_POST_JSON, null, this, 0);
    }

    private void requesList(int page) {
        params = this.getArguments().getString(ARG_PARAM);
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String[] param = {params, String.valueOf(page), timeStamp, "15"};
        String url_news = UrlUtils.convertUrl(param, Urls.NEWS_LIST);
        HttpUtils.getInstance(getActivity()).requestAsyn(url_news, HttpUtils.TYPE_POST_JSON, null, this, 1);
    }


    @Override
    public void onSelected(int position) {
        //轮播图的选中监听事件
        carousel_title.setText(mTitles.get(position));
        carousel_page.setText((position + 1) + "/" + mTitles.size());
    }

    @Override
    public void onImgClick(int position) {
        //轮播图的点击事件，同新闻列表
        String nid = mBannerList.get(position).getId();
        String title = mBannerList.get(position).getTitle();
        Intent intent = new Intent();
        intent.setClass(getActivity(), NewsDetailActivity.class);
        intent.putExtra("nid", nid);
        intent.putExtra("title", title);
        startActivity(intent);
    }

    @Override
    public void onReqSuccess(String result, int flag) {
        stopLoading();
        //如果PullToRefreshListView还在刷新，就取消掉
        if (refreshListView.isRefreshing()) {
            refreshListView.onRefreshComplete();
        }
        //如果当前只有一个页面并且有数据，就取消掉本次网络请求成功后的所有操作
        if (page == 0 && mNewsListBean.size() > 0) {
            return;
        }
        //flag用来判断当前的是轮播图的网络请求还是新闻列表的
        switch (flag) {
            case 0:
                mImages.clear();
                mTitles.clear();
                mBannerList.clear();
                BannerModel entity = GsonUtils.json2Bean(result, BannerModel.class);
                for (BannerModel.DataBean.ImglistBean bean : entity.getData().getImglist()) {
                    mImages.add(Urls.IMG_URL + bean.getThumb());
                    mTitles.add(bean.getTitle());
                    mBannerList.add(bean);
                }
                //利用轮播图工具类BannerUtils生成一个轮播图
                BannerUtils bannerUtils = new BannerUtils();
                bannerUtils.setOnPageSelected(this);
                bannerUtils.initHeadView(mImages, getActivity(), vp_carousel);
                break;
            case 1:
                NewsListModel newsListModel = GsonUtils.json2Bean(result, NewsListModel.class);
                mNewsListBean.addAll(newsListModel.getData().getNews_list());
                mNewsListItemAdapter.notifyDataSetChanged();
                //设置PullToRefreshListView为可以同时支持上拉和下拉
                refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                break;
        }
    }

    @Override
    public void onReqFailed(String errorMsg, int flag) {
        showLoading();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        requestWebData(1);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        Toast.makeText(getActivity(), "请检查您的网络", Toast.LENGTH_SHORT).show();
    }
}
